import { debounce } from 'lodash-es'
import { ElPagination } from 'element-plus'
import { defineComponent, onMounted, ref, h } from 'vue'
import type { VNode, FunctionalComponent, EmitsOptions } from 'vue'
import type { Slots } from './index'
import { usePagin } from '@v-model/shared--hooks'

import './main.scss'

export default defineComponent({
  name: 'VMain',
  props: {},
  setup(props, { slots, attrs, emit }: { slots: Slots; attrs: any; emit: EmitsOptions }) {
    const Main = ref<HTMLDivElement | null>(null)
    const tops = ref<HTMLDivElement | null>(null)
    const foot = ref<HTMLDivElement | null>(null)

    const tableHeight = ref<number>(0)
    onMounted(() => {
      window.addEventListener('resize', debounce(handleHeight, 500), true)
      handleHeight()
    })

    // const emits = defineEmits(['sizeChange'])

    function handlerFilter() {}

    const usepages = usePagin(handlerFilter)

    const handleHeight = (): void => {
      const MainHeight: number = document.body.clientHeight - 132 // headers 和 tags 高度
      try {
        tableHeight.value = MainHeight - (tops.value?.offsetHeight || 0) - (foot.value?.offsetHeight || 0)
      } catch (err) {
        console.warn('Calculation had error about Main.vue', err)
      }
    }

    // 头部内容区域
    const Header: FunctionalComponent = (): VNode | null =>
      slots.header ? h('div', { class: 'query-header', ref: tops }, [slots['header']?.()]) : null

    // Main 内容展示区域
    const Content: FunctionalComponent = (): VNode =>
      h('div', { class: 'default-main', ref: Main }, [
        slots['default']?.({
          tableHeight: tableHeight.value,
        }),
      ])

    // 使用默认分页参数
    const defaultPagin = () =>
      h(ElPagination, {
        // ...usepages.pagesState,
        currentPage: usepages.pageNum.value,
        'onUpdate:currentPage': (value: number) => (usepages.pageNum.value = value),
        onSizeChange: usepages.handleSizeChange,
        onCurrentChange: usepages.handleCurrentChange,
        class: 'pageFooter',
        ref: foot,
      })

    // 页面底部
    const PageFooter: FunctionalComponent = (): VNode | null => {
      // 使用默认分页
      if (attrs.total) return defaultPagin()

      return slots.pageFooter ? h('div', { class: 'pageFooter', ref: foot }, [slots.pageFooter?.()]) : null
    }

    return (): VNode => h('div', { class: 'main-content' }, [Header(), Content(), PageFooter()])
  },
})
